package com.qq5194102.simpleskills.skill.sword;
import com.qq5194102.simpleskills.core.PlayerDataManager;
import com.qq5194102.simpleskills.util.SwordUtil;
import org.bukkit.*;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Monster;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector;

import java.util.*;

/**
 * @Author caiyh
 * @Date 2025/7/22 20:07
 * @Description
 */
public class SwordActiveSkill implements Listener{
    private final JavaPlugin plugin;
    private final Map<UUID, Long> cooldowns = new HashMap<>();
    private final Map<UUID, Long> lastMessageTime = new HashMap<>(); // 新增：记录上次发送消息的时间
    private final long MESSAGE_COOLDOWN = 2 * 1000; // 消息冷却时间2秒

    public SwordActiveSkill(JavaPlugin plugin) {
        this.plugin = plugin;
    }

    // 监听右键怪物 执行技能触发
    @EventHandler
    public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
        Entity entity = event.getRightClicked();

        // 检查是否右键点击了怪物
        if (entity instanceof Monster) {
            activeSkill(event.getPlayer());
        }
    }


    // 监听右键空气 执行技能触发
    @EventHandler
    public void onPlayerInteract(PlayerInteractEvent event) {
        // 检查是否右键空气
        if (event.getAction() == Action.RIGHT_CLICK_AIR) {
            activeSkill(event.getPlayer());
        }

    }

    // 技能触发  判断是否符合条件
    private void activeSkill(Player player){
        // 检查是否持剑
        if (!SwordUtil.playerMainHandIsSword(player)) {
            return;
        }

        // 检查冷却时间
        long currentTime = System.currentTimeMillis();
        UUID playerId = player.getUniqueId();

        if (cooldowns.containsKey(playerId)) {
            long lastUse = cooldowns.get(playerId);
            long cooldownRemaining = getActiveSkillColdDown(player) - (currentTime - lastUse);

            if (cooldownRemaining > 0) {
                // 检查消息冷却时间
                long lastMsgTime = lastMessageTime.getOrDefault(playerId, 0L);
                if (currentTime - lastMsgTime > MESSAGE_COOLDOWN) {
                    long remainingSeconds = cooldownRemaining / 1000;
                    player.sendMessage(ChatColor.RED + "技能冷却中，还剩 " + remainingSeconds + " 秒");
                    lastMessageTime.put(playerId, currentTime); // 更新消息发送时间
                }
                return;
            }
        }

        // 设置冷却时间
        cooldowns.put(playerId, currentTime);
        // 清除消息冷却时间
        lastMessageTime.remove(playerId);

        // 执行斩技能
        executeSlash(player);
    }

    // 执行技能
    private void executeSlash(Player player) {
        // 播放释放音效
        //player.getWorld().playSound(player.getLocation(), Sound.ENTITY_PLAYER_ATTACK_SWEEP, 1.0f, 1.0f);

        // 播放玩家动画
        //player.swingMainHand();

        // 执行斩
        new BukkitRunnable() {
            int stage = 0;

            @Override
            public void run() {
                if (stage >= 1) {
                    this.cancel();
                    return;
                }

                // 发射剑气
                launchSwordWave(player);

                stage++;
            }
        }.runTaskTimer(plugin, 0, 10); // 每5tick(0.5秒)发射一段
    }

    // 发射剑气
    private void launchSwordWave(Player player) {
        Location startLoc = player.getEyeLocation().clone();
        Vector direction = startLoc.getDirection().normalize();

        // 根据阶段调整伤害和特效
        double damage = getActiveSkillDamage(player);

        // 播放剑气音效
//        player.getWorld().playSound(startLoc, Sound.ENTITY_FIREWORK_SHOOT, 0.8f, 1.0f + (stage * 0.2f));
        player.getWorld().playSound(startLoc, Sound.ENTITY_FIREWORK_LAUNCH, 0.8f, 1.0f);
        List<Monster> monsters = new ArrayList<>();

        new BukkitRunnable() {
            double distance = 0;
            final double maxDistance = getActiveSkillDistance(player); // 最大距离10格
            final double speed = 1; // 每tick移动距离

            @Override
            public void run() {
                if (distance >= maxDistance) {
                    // 取消技能标记 下次技能就可以继续攻击
                    for (Monster monster : monsters) {
                        monster.removeMetadata("slash_hit",plugin);
                    }
                    this.cancel();
                    return;
                }

                // 计算当前位置
                distance += speed;
                Location currentLoc = startLoc.clone().add(direction.clone().multiply(distance));

                // 显示剑气特效
                showWaveEffect(currentLoc);

                // 检测并伤害实体
                for (Entity entity : currentLoc.getWorld().getNearbyEntities(currentLoc, 0.8, 0.8, 0.8)) {
                    if (entity instanceof Monster) {
                        Monster target = (Monster) entity;

                        // 避免重复伤害
                        if (!target.hasMetadata("slash_hit")) {
                            target.damage(damage, player);
                            monsters.add(target);
                            target.setMetadata("slash_hit", new FixedMetadataValue(plugin, true));

                            // 短暂后移效果
                            Vector knockback = direction.clone().multiply(0.5);
                            target.setVelocity(knockback);

                            // 显示命中特效
                            showHitEffect(target.getLocation());
                        }
                    }
                }
            }
        }.runTaskTimer(plugin, 0, 1); // 每tick移动一次
    }

    // 显示剑气特效
    private void showWaveEffect(Location loc) {
        World world = loc.getWorld();
        if (world == null) return;


        // 辅助粒子效果 - 使用暴击粒子
        world.spawnParticle(Particle.CRIT, loc, 5, 0.3, 0.3, 0.3, 0.05);

        // 剑气轨迹 - 使用火焰粒子
        for (int i = 0; i < 3; i++) {
            Location trailLoc = loc.clone().add(
                    (Math.random() - 0.5) * 0.7,
                    (Math.random() - 0.5) * 0.7,
                    (Math.random() - 0.5) * 0.7
            );

            // 红色剑气使用火焰粒子，其他使用水滴粒子
            Particle trailParticle = Particle.WATER_DROP;
            world.spawnParticle(trailParticle, trailLoc, 2, 0, 0, 0, 0.05);
        }
    }

    // 显示命中特效
    private void showHitEffect(Location loc) {
        World world = loc.getWorld();
        if (world == null) return;

        // 命中粒子效果
        world.spawnParticle(Particle.FLAME, loc, 15, 0.5, 0.5, 0.5, 0.1);
        world.spawnParticle(Particle.CRIT_MAGIC, loc, 10, 0.5, 0.5, 0.5, 0.2);

        // 命中音效
        world.playSound(loc, Sound.ENTITY_PLAYER_ATTACK_CRIT, 0.8f, 1.2f);
    }


    private double getActiveSkillDamage(Player player){
        return PlayerDataManager.getPlayerData(player.getUniqueId()).getSwordSkillData().getActiveSkillDamage();
    }
    private double getActiveSkillDistance(Player player){
        return PlayerDataManager.getPlayerData(player.getUniqueId()).getSwordSkillData().getActiveDistance();
    }
    private long getActiveSkillColdDown(Player player){
        return PlayerDataManager.getPlayerData(player.getUniqueId()).getSwordSkillData().getActiveColdDown();
    }
}